package com.dacong.nezha.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dacong.nezha.domain.*;
import com.dacong.nezha.service.*;
import com.dacong.nezha.utils.AesUtil;
import com.dacong.nezha.utils.ExcuteHttp;
import javafx.scene.paint.Color;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class IndexController {

    @Autowired
    ActiveService activeService;

    @Autowired
    BindAccountService bindAccountService;

    @Autowired
    AccountConfigService accountConfigService;

    @Autowired
    ApiService apiService;

    @Autowired
    ServerListService serverListService;



    @GetMapping("/access/{code}")
    public R access(HttpServletRequest request, @PathVariable("code") String code){
        String version = request.getHeader("version");
        String machineId = request.getHeader("machineId");
        String username = request.getHeader("username");
        log.info("机器码:{} 账户:{} 版本:{} IP:{}",machineId,username,version,request.getRemoteAddr());
        Active one = activeService.lambdaQuery()
                .eq(Active::getCode, code)
                .one();
        if (one == null){
            Active active = new Active();
            active.setCode(code);
            active.setAuthNum(0);
            boolean save = activeService.save(active);
            return R.ok(active);
        }else{
            if (one.getBlack() == 1){
                return null;
            }
            return R.ok(one);
        }
    }

    @GetMapping("/bind/{code}/{account}")
    public R bindAccount(@PathVariable("code") String code,@PathVariable("account") String account){
        Boolean bind = bindAccountService.bind(code, account);
        return R.ok(bind);
    }

    @GetMapping("/getAccountConfig/{account}")
    public R getAccountConfig(@PathVariable("account") String account){
        AccountConfig accountConfig = accountConfigService.lambdaQuery()
                .eq(AccountConfig::getAccount, account)
                .one();
        return R.ok(accountConfig);
    }

    @PostMapping("/saveAccountConfig/{account}")
    public R getAccountConfig(@PathVariable("account") String account,@RequestBody String config){
        AccountConfig accountConfig = new AccountConfig();
        accountConfig.setAccount(account);
        accountConfig.setConfig(config);
        boolean save = accountConfigService.save(accountConfig);
        return R.ok(save);
    }

    @GetMapping("/proxy")
    public R getProxy(){
        String url = "http://api.shenlongip.com/ip?key=lnv2ej9z&protocol=1&mr=1&pattern=json&need=1001&count=1&sign=b8e5b19dff4a387297a2c511ce249919";
        String s = HttpUtil.get(url);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        Integer code = jsonObject.getInt("code");
        String msg = jsonObject.getStr("msg");
        if (code == 200) {
            JSONArray data = jsonObject.getJSONArray("data");
            JSONObject jsonObject1 = data.getJSONObject(0);
            return R.ok(jsonObject1);
        }else{
            log.error("code: {} msg: {}",code,msg);
            return R.fail();
        }

    }

    @GetMapping("/serverList")
    public R serverList(HttpServletRequest request){
        String machineId = request.getHeader("machineId");
        if (StrUtil.isNotBlank(machineId)) {
            List<CodeServerList> list = serverListService.getByCode(machineId);
            if (list.isEmpty()){
                List<ServerList> all = serverListService.list();
                return R.ok(all);
            }
            return R.ok(list);
        }else{
            List<ServerList> list = serverListService.list();
            return R.ok(list);
        }
    }

    @PostMapping("/login")
    public R login(@RequestBody String body){

        JSONObject entries1 = JSONUtil.parseObj(body);

        String username = entries1.getStr("username");
        String password = entries1.getStr("password");
        String code = entries1.getStr("code");

        String reqbody ="{\n" +
                "    \"url\": \"/auth/login\",\n" +
                "    \"options\": {\n" +
                "        \"method\": \"POST\",\n" +
                "        \"body\": \"{\\\"loginCode\\\":\\\""+username+"\\\",\\\"password\\\":\\\""+ AesUtil.rsa(password)+"\\\",\\\"authenticatorCode\\\":\\\""+code+"\\\",\\\"machineCode\\\":\\\"21dad7e8502a6253495d072b0ca1383163fbd187abfe628c326f5fe96d9c0d81+74:56:3c:cf:9e:53\\\",\\\"version\\\":\\\"2.11.0\\\"}\",\n" +
                "        \"headers\": {\n" +
                "            \"Content-Type\": \"application/json\",\n" +
                "            \"Language\": \"zh-CN\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        String resp = ExcuteHttp.executeHttp(reqbody);

        JSONObject entries = JSONUtil.parseObj(resp);
        Integer code1 = entries.getInt("code");
        String message = entries.getStr("message");
        if (code1 == 0) {
            String token = entries.getJSONObject("data").getStr("token");
            return R.ok(token);
        }
        return R.fail();
    }

    @PostMapping("/action")
    public R work(@RequestBody String body){

        JSONObject jsonObject = JSONUtil.parseObj(body);
        String action = jsonObject.getStr("action");
        String token = jsonObject.getStr("token");
        if ("yanghao".equals(action)) {
            String yanghao = apiService.yanghao(token);
            return R.ok(yanghao);
        } else if ("xiadan".equals(action)) {
            String xiadan = apiService.xiadan(token);
            return R.ok(xiadan);
        }else if ("fuhuo".equals(action)) {
            String fuhuo = apiService.fuhuo(token);
            return R.ok(fuhuo);
        }else if ("shensu".equals(action)) {
            String shensu = apiService.shensu(token);
            return R.ok(shensu);
        }else if ("tuikuan".equals(action)) {
            String tuikuan = apiService.tuikuan(token);
            return R.ok(tuikuan);
        }else if ("tongji".equals(action)) {
            Map<String, Object> tongji = apiService.tongji(token);
            return R.ok(tongji);
        }else if ("buyCk".equals(action)) {
            Integer num = jsonObject.getInt("num");
            String buyCk = apiService.buyCk(num, token);
            return R.ok(buyCk);
        }else if ("buySlink".equals(action)) {
            Integer num = jsonObject.getInt("num");
            String buySlink = apiService.buySlink(num, token);
            return R.ok(buySlink);
        }

        return R.ok();
    }

}
